package com.shark.demo;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName ThreadLocalPoolSaleTicket
 * @Description TODO
 * @Author 东北彭于晏
 * @Date 2024/10/8  17:00
 * @Version 1.0
 **/
public class ThreadLocalPoolSaleTicket {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                Runtime.getRuntime().availableProcessors(),
                Runtime.getRuntime().availableProcessors()*2,
                3L,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(5),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );

        Tickets tickets = new Tickets();

        try {
            for (int i = 0; i < 50; i++) {
                threadPoolExecutor.execute(tickets::saleTicket);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            threadPoolExecutor.shutdown();
        }


    }
}
class Tickets{
    private Integer number = 50;

    Lock lock = new ReentrantLock();
    public void saleTicket() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出 :" + (number--) + "-------还剩 :" + number);
                TimeUnit.MILLISECONDS.sleep(10);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}